package com.cskaoyan.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

//先认证后授权
@Component
public class CustomRealm extends AuthorizingRealm {
    /**
     * @param authenticationToken subject执行login的时候传入的token
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //提供认证信息 👉 credentials
        //系统中保存的用户名和对应的credentials和上面的一些信息一致
        String credentials = null;
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        //-------
        if ("songge".equals(username)) { //这部分业务 应该是根据token中传入的username通过数据库查询获得的
            credentials = "niupile";
        } else if ("ligenli".equals(username)) {
            credentials = "daqi";
        } else {
            credentials = "qiezi";
        }
        //-------
        //第一个参数Principal：就是主角信息，在后面授权的时候可以获得这个值，Session中的principal信息
        //                   你传入一个什么样的principal信息，认证成功之后就能够获得什么样的principal
        //第二个参数credentials：会和token中的password做比对
        return new SimpleAuthenticationInfo(username,credentials,this.getName());
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权 → 提供权限
        //获得principal信息
        //获得doGetAuthen方法（上面这个方法），构造的authenticationInfo中的principal信息
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        //根据principal信息可以查询对应的权限信息
        List<String> permissions = selectPermissionsByPrincipalFromDb(primaryPrincipal);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permissions);//提供权限 👉 找到所有的钥匙

        return authorizationInfo;
    }

    private List<String> selectPermissionsByPrincipalFromDb(String primaryPrincipal) {
        if ("ligenli".equals(primaryPrincipal)) {
            return Arrays.asList("teach", "eat", "sleep");
        }
        if ("songge".equals(primaryPrincipal)) {
            return Arrays.asList("run", "sleep");
        }

        return null;
    }

}
